<?php

namespace App\Console\Commands\User;

use App\Console\Commands\DemoCommand;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Common\FsCompanyUserModel;
use App\Models\Feishu\FsLoginLogModel;
use Illuminate\Console\Command;

class ExtUserLoginLogDumpCommand extends Command
{
    protected $signature = 'user:ext-user-login-log-dump';

    protected $description = '供应商用户登录日志导出';

    private array $lists;

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        FsCompanyUserModel::query()->where('ext', 1)->where('rmsUserId', '>', 0)->groupBy('rmsUserId')->get()->map(function ($item) {

            $log = FsLoginLogModel::query()->where('userId', $item->rmsUserId)->orderByDesc('id')->first();

            $companyName = '';

            $fsCompanyIds = FsCompanyUserMappingModel::query()->where('rmsUserId', $item->rmsUserId)->pluck('fsCompanyId')->toArray();
            if ($fsCompanyIds) {
                $companys = FsCompanyModel::query()->whereIn('id', $fsCompanyIds)->get();
                foreach ($companys as $company) {
                    $companyName .= "机构{$company->organizationId}:{$company->name},";
                }
                $companyName = rtrim($companyName, ',');
            }

            return $this->lists[] = [
                $item->phone,
                $item->name,
                $log ? date('Y-m-d H:i:s', $log->createdAt) : '--',
                $companyName
            ];
        });

        DemoCommand::export(['手机', '姓名', '最后登录时间（--表示2023.11.13后，未登录过）', '公司名称'], $this->lists);
    }
}
